<template>
  <div class="questionnaire-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>问卷列表</span>
          <el-button type="primary" @click="handleAdd">新增问卷</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="questionnaires"
        style="width: 100%"
      >
        <el-table-column
          prop="title"
          label="标题"
          min-width="200"
        />
        <el-table-column
          prop="description"
          label="描述"
          min-width="300"
        />
        <el-table-column
          prop="status"
          label="状态"
          width="100"
        >
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="300"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
              v-if="isAdmin || scope.row.creatorId === currentUserId"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              v-if="(isAdmin || scope.row.creatorId === currentUserId) && scope.row.status === 0"
              @click="handlePublish(scope.row)"
            >
              发布
            </el-button>
            <el-button
              type="warning"
              link
              v-if="(isAdmin || scope.row.creatorId === currentUserId) && scope.row.status === 1"
              @click="handleEnd(scope.row)"
            >
              结束
            </el-button>


            <el-button
              type="danger"
              link
              v-if="isAdmin || scope.row.creatorId === currentUserId"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getList, remove, publish, end } from '@/api/questionnaire'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const questionnaires = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const isAdmin = computed(() => userStore.user?.role === 1)
const currentUserId = computed(() => userStore.user?.id)

// 加载问卷列表
const loadQuestionnaires = async () => {
  loading.value = true
  try {
    const res = await getList({
      page: currentPage.value,
      size: pageSize.value
    })
    if (res.code === 200) {
      questionnaires.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('加载问卷列表失败:', error)
    ElMessage.error('加载问卷列表失败')
  } finally {
    loading.value = false
  }
}

// 新增问卷
const handleAdd = () => {
  router.push('/admin/questionnaire/add')
}

// 编辑问卷
const handleEdit = (row) => {
  console.log('编辑问卷:', row)
  router.push(`/admin/questionnaire/edit/${row.id}`)
}

// 发布问卷
const handlePublish = async (row) => {
  try {
    console.log('发布问卷:', row)
    const res = await publish(row.id)
    if (res.code === 200) {
      ElMessage.success('发布成功')
      await loadQuestionnaires()
    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败')
  }
}

// 结束问卷
const handleEnd = async (row) => {
  try {
    console.log('结束问卷:', row)
    const res = await end(row.id)
    if (res.code === 200) {
      ElMessage.success('已结束')
      await loadQuestionnaires()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('结束失败:', error)
    ElMessage.error('操作失败')
  }
}

// 查看统计
const handleStatistics = (row) => {
  console.log('查看统计:', row)
  router.push({
    name: 'QuestionnaireStatistics',
    params: { id: row.id }
  })
}

// 删除问卷
const handleDelete = (row) => {
  console.log('删除问卷:', row)
  ElMessageBox.confirm(
    '确定要删除这个问卷吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const res = await remove(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        await loadQuestionnaires()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 填写问卷
const handleSubmit = (row) => {
  router.push(`/questionnaire/submit/${row.id}`)
}

// 状态相关
const getStatusType = (status) => {
  const map = {
    0: 'info',
    1: 'success',
    2: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    0: '未发布',
    1: '已发布',
    2: '已结束'
  }
  return map[status] || '未知'
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  loadQuestionnaires()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadQuestionnaires()
}

onMounted(() => {
  loadQuestionnaires()
})
</script>

<style scoped>
.questionnaire-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 确保操作列按钮在一行显示 */
:deep(.el-table .cell) {
  white-space: nowrap;
}

/* 按钮间距 */
.el-button + .el-button {
  margin-left: 8px;
}
</style>
